package com.practica.superTrivia;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import android.graphics.*;
import android.os.*;

public class HttpConnection implements Runnable {

	public static final int DID_START = 0;
	public static final int DID_ERROR = 1;
	public static final int DID_SUCCEED = 2;

	private static final int GET = 0;
	private static final int POST = 1;
	private static final int PUT = 2;
	private static final int DELETE = 3;
	private static final int BITMAP = 4;

	private String url;
	private int method;
	private Handler handler;
	private String data;
	private String pair1;
	private String pair2;

	private HttpClient httpClient;

	public HttpConnection() {
		this(new Handler());
	}

	public HttpConnection(Handler _handler) {
		handler = _handler;
	}

	public void create(int method, String url, String pair1, String pair2) {
		this.method = method;
		this.url = url;
		this.pair1 = pair1;
		this.pair2 = pair2;
		ConnectionManager.getInstance().push(this);
	}

	public void get(String url, String data) {
		create(GET, url, data, null);
	}

	public void post(String url, String pair1, String pair2) {
		create(POST, url, pair1, pair2);
	}

	public void put(String url, String pair1, String pair2) {
		create(PUT, url, pair1, pair2);
	}

	public void delete(String url) {
		create(DELETE, url, null, null);
	}

	public void run() {
		handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
		httpClient = new DefaultHttpClient();
		List<NameValuePair> pairs;
		HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
		try {
			HttpResponse response = null;
			switch (method) {
			case GET:
				pairs = new ArrayList<NameValuePair>();
				pairs.add(new BasicNameValuePair("email", pair1));
				HttpGet get_request = new HttpGet(url + "?"+ URLEncodedUtils.format(pairs, "utf-8")); 
				get_request.setHeader("Accept", "application/json");
				response = httpClient.execute(get_request);
				break;
			case POST:
				HttpPost httpPost = new HttpPost(url);
				pairs = new ArrayList<NameValuePair>();
				pairs.add(new BasicNameValuePair("email", pair1));
				pairs.add(new BasicNameValuePair("friend_address", pair2));
				httpPost.setEntity(new UrlEncodedFormEntity(pairs));
				response = httpClient.execute(httpPost);
				break;
			case PUT:
				HttpPut httpPut = new HttpPut(url);
				httpPut.setEntity(new StringEntity(data));
				response = httpClient.execute(httpPut);
				break;
			case DELETE:
				response = httpClient.execute(new HttpDelete(url));
				break;
			}
			if (method == GET)
				processEntity(response.getEntity());
		} catch (Exception e) {
			handler.sendMessage(Message.obtain(handler,
					HttpConnection.DID_ERROR, e));
		}
		ConnectionManager.getInstance().didComplete(this);
	}

	private void processEntity(HttpEntity entity) throws IllegalStateException,
			IOException, JSONException {
		InputStream stream = entity.getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null)
		{
			sb.append(line + "\n");
		}
		stream.close();
		String responseString = sb.toString();
		GsonBuilder builder = new GsonBuilder();
		Gson gson = builder.create();
		JSONObject json = new JSONObject(responseString);
		HighScoreList myClass = gson.fromJson(json.toString(), HighScoreList.class);
		
		Message message = Message.obtain(handler, DID_SUCCEED, myClass);
		handler.sendMessage(message);
	}
}
